﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace System
{
    public static class ByteExtend
    {
        /// <summary>
        /// ASCII编码
        /// </summary>
        public static Encoding ASCII = Encoding.ASCII;
        /// <summary>
        /// 字节转十六进制时十六进制字符串代码表
        /// </summary>
        private static byte[] mHexDigits;
        /// <summary>
        /// 初始化十六进制转换字典
        /// </summary>
        static ByteExtend()
        {
            mHexDigits = ASCII.GetBytes("0123456789ABCDEF");
        }
        /// <summary>
        /// 字节转十六进制
        /// </summary>
        /// <param name="bData"></param>
        /// <returns></returns>
        /// <remarks></remarks>
        public static string ToHex(this byte[] bData)
        {
            byte[] bHex;
            int i;
            int lIndex;

            if (bData.Length == 0)
                return "00";
            int ilen = bData.Length;
            // 初始化操作
            bHex = new byte[ilen * 2];

            // 开始转换
            lIndex = 0;
            for (i = 0; i < ilen; i++)
            {
                bHex[lIndex] = mHexDigits[bData[i] / 16]; lIndex = lIndex + 1;
                bHex[lIndex] = mHexDigits[bData[i] % 16]; lIndex = lIndex + 1;
            }

            return ASCII.GetString(bHex).TrimEnd('\0');
        }

        public static string GetString(this byte[] bData)
        {
            return Encoding.UTF8.GetString(bData);
        }
    }
}
